import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:bubble_box/bubble_box.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_ncsjqz_getx/constant/constant.dart';
import 'package:flutter_ncsjqz_getx/model/login_entity.dart';
import 'package:flutter_ncsjqz_getx/page_common/show_img_page.dart';
import 'package:flutter_ncsjqz_getx/page_common/show_video_page.dart';
import 'package:flutter_ncsjqz_getx/util/get_user_util.dart';
import 'package:flutter_ncsjqz_getx/util/time.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:get/get.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';

import '../chat_setting/group/chats_setting_view.dart';
import '../chat_setting/private/chat_setting_view.dart';
import '../util/media_util.dart';
import '../util/rong_bottom_sheet_widget.dart';
import '../util/rong_emoji.dart';
import '../util/rong_widget.dart';
import 'chat_logic.dart';

/// <summary>
/// author：zwb
/// dateTime： 2021/12/14 11:17
/// filePath： lib/page/rong_im/chat_view.dart
/// desc: 聊天页面
/// <summary>
///
class ChatPage extends StatefulWidget {
  // 用户昵称
  final String? title;
  // 用户头像
  final String? userPic;
  // 会话id
  final String? targetId;
  // 消息id
  final String? messageId;
  // 好友id
  final int? friendId;
  // 1=单聊 3=群聊
  final int? conversationType;
  // 1群主 2成员
  final int? groupType;
  // 用于处理返回到哪个页面 ，0 从好友列表进入  1 从好友信息进入 3 从会话进入
  final int? current;
  ChatPage({this.conversationType:1, this.current: 3,this.title, this.targetId, this.userPic, this.friendId, this.messageId, this.groupType});
  @override
  _ChatPageState createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage>  with WidgetsBindingObserver{
  final logic = Get.put(ChatLogic());

  // 键盘高度
  double bottom = 0.0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    init();
  }

  /// 初始化
  init () async {
    MediaUtil.getInstance()!.requestPermissions();
    // 创建一个界面变化的观察者
    WidgetsBinding.instance!.addObserver(this);
    logic.emojiList =  Emoji.emojiList;
    logic.privateUserId = widget.targetId ?? '';
    logic.usePic = widget.userPic;
    logic.name = widget.title;
    logic.conversationType = widget.conversationType ?? 1;
    await logic.getMessageList();
    logic.messageListEvent();
    // 消息列表滚动到最后
    logic.setListMax();
    logic.update();
  }

  /// 窗口变化监听
  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    WidgetsBinding.instance!.addPostFrameCallback((_) {
      bottom = MediaQuery.of(context).viewInsets.bottom;
      if (Platform.isAndroid && logic.focusNode.hasFocus &&  MediaQuery.of(context).viewInsets.bottom > 0){
        logic.setListMax();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ChatLogic>(
      builder: (controller) {
        return WillPopScope(child: Scaffold(
          appBar: RongWidget.appBarWidget(title: "${widget.title}",actions: [
            Padding(
              padding: EdgeInsets.only(right: 15),
              child: RongWidget.imgAsset("setting1.png",onTap: (){
                Get.to(()=> widget.conversationType == 1 ? ChatSettingPage(ryUserId: widget.targetId!,friendId: widget.friendId,) : ChatsSettingPage(groupType: widget.groupType ??0 ,groupId: widget.targetId ?? '',));
              },width: 20),
            )
          ],),
          backgroundColor: Colors.white,
          resizeToAvoidBottomInset: true,
          body: Column(
            children: [
              Expanded(
                child: GestureDetector(
                  child: EasyRefresh(
                    header: CustomHeader(
                        extent: 40.0,
                        triggerDistance: 50.0,
                        headerBuilder: (context,
                            loadState,
                            pulledExtent,
                            loadTriggerPullDistance,
                            loadIndicatorExtent,
                            axisDirection,
                            float,
                            completeDuration,
                            enableInfiniteLoad,
                            success,
                            noMore) {
                          return Stack(
                            children: <Widget>[
                              Positioned(
                                bottom: 0.0,
                                left: 0.0,
                                right: 0.0,
                                child: Container(
                                  width: 30.0,
                                  height: 30.0,
                                  child: SpinKitCircle(
                                    color: Colors.green,
                                    size: 30.0,
                                  ),
                                ),
                              ),
                            ],
                          );
                        }),
                    scrollController: logic.scrollController,
                    child: Container(
                      child: ListView(
                        physics: NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        reverse: true,
                        padding: EdgeInsets.all(0),
                        children: [
                          ...List.generate(logic.msgList.length, (index){
                            return Column(
                              children: [
                                Container(
                                  alignment: Alignment.center,
                                  child: Text(
                                    '${logic.msgList[index].timer}',
                                    style: TextStyle(color: Colors.grey.shade400, fontSize: 13),
                                  ),
                                ),
                                messageItem(index) ?? SizedBox(),
                              ],
                            );
                          }),
                        ],
                      ),
                    ),
                    onRefresh: () async{
                      print("刷新消息");
                      //加载历史记录
                      logic.pageIndex++;
                      logic.getMessageList();
                    },
                  ),
                  onPanDown: ((details){
                    /// 触摸列表 失去焦点
                    logic.focusNode.unfocus();
                    /// 触摸列表 关闭底部工具栏
                    if(logic.showBottom) logic.setShowBottom();
                    /// 键盘弹出时  触摸列表将消息列表滑到到最后
                    if(bottom > 0.0) logic.setListMax();
                  }),
                ),
              ),
              Divider(height: 1,color: Colors.grey.shade300,),
              bottomTabUtil(),
            ],
          ),

        ), onWillPop: () async{
          // Get.back();
          return true;
        });
      },
    );
  }

  /// 每条消息体
  Widget? messageItem(index){
    // 获取自己的用户信息
    LoginData? loginData = getUserUtil();
    // 消息撤回
    if(logic.msgList[index].content  is RecallNotificationMessage){
      return buildRecallNotificationMessage(index);
    }
    // 群组消息
    if(logic.msgList[index].content is GroupNotificationMessage){
      return buildGroupNotificationMessage(index);
    }
    return Container(
      // logic.msgList[index].ryUserId == loginData.ryUserId  自己发的消息 or 别人发的消息
      child: logic.msgList[index].ryUserId == loginData.ryUserId ? Row(
        mainAxisAlignment: MainAxisAlignment.end,
        // 图片消息 对齐
        crossAxisAlignment: logic.msgList[index].content is ImageMessage ?CrossAxisAlignment.start : CrossAxisAlignment.center,
        children: [
          BubbleBox(
            maxWidth: Get.width * 0.6,
            child: msgTyToMsg(index),
            backgroundColor: Colors.grey.shade100,
          ),
          RongWidget.imgNet(
            '${logic.msgList[index].cover}',
            onTap: (){
              print("点击了我头像");
            },
            padding: EdgeInsets.only(left: 15),
            width: 50,height: 50,borderRadius: BorderRadius.circular(5),
          ),
        ],
      ) :  Row(
        mainAxisAlignment: MainAxisAlignment.start,
        // 图片消息 对齐
        crossAxisAlignment: logic.msgList[index].content is ImageMessage ?CrossAxisAlignment.start : CrossAxisAlignment.center,
        children: [
          RongWidget.imgNet(
            '${logic.msgList[index].cover}',
            onTap: (){
              print("点击了对方头像");
              Get.to(()=> widget.conversationType == 1 ? ChatSettingPage(ryUserId: widget.targetId,friendId: widget.friendId) : ChatsSettingPage(groupType: widget.groupType ?? 0,groupId: widget.targetId ?? '',));
            },
            padding: EdgeInsets.only(right: 15),
            width: 50,height: 50,borderRadius: BorderRadius.circular(5),
          ),
          BubbleBox(
            backgroundColor: Colors.grey.shade100,
            maxWidth: Get.width * 0.6,
            child:  msgTyToMsg(index),
          )
        ],
      ),
      padding: EdgeInsets.symmetric(vertical: 10,horizontal: 15),
    );
  }

  /// 根据消息类型 返回符合的显示
  Widget msgTyToMsg(int index){
    Widget widget = SizedBox();
    // 语音文件
    if(logic.msgList[index].content is VoiceMessage){
      widget = voicePlayWidget(index);
    }
    // 文本消息
    if (logic.msgList[index].content is TextMessage) {
      widget = Text('${logic.msgList[index].msg}',style: TextStyle(fontSize: 16, color: Colors.black),);
    }
    // 图片消息
    if (logic.msgList[index].content is ImageMessage) {
      ImageMessage image = logic.msgList[index].content as ImageMessage;
      Uint8List bytes = Base64Decoder().convert(image.content!);
      widget =  InkWell(
        child: Image.memory(bytes, height: 140, width: 100,
          // fit: BoxFit.fill, //填充
          gaplessPlayback: true, //防止重绘
          cacheWidth: 100,
          cacheHeight: 140,
          fit: BoxFit.cover,
        ),
        onTap: (){
          String localPath;
          String remoteUrl;
          ImageProvider imageProvider;
          MessageContent message = logic.msgList[index].content!;
          if (message is GifMessage) {
            GifMessage msg = message;
            localPath = msg.localPath!;
            remoteUrl = msg.remoteUrl!;
          } else {
            ImageMessage msg = message as ImageMessage;
            localPath = msg.localPath ??'';
            remoteUrl = msg.imageUri ?? '';
          }
          if (localPath != null) {
            String path = MediaUtil.instance!.getCorrectedLocalPath(localPath);
            File file = File(path);
            if (file != null && file.existsSync()) {
              imageProvider =FileImage(file);
            } else {
              imageProvider =NetworkImage(remoteUrl);
            }
          } else {
            imageProvider =NetworkImage(remoteUrl);
          }
          // 查看大图
          Get.to(ShowImg(imgs: [
            remoteUrl
          ],showTop: false,));
        },
      );
    }
    // 视频消息
    if (logic.msgList[index].content  is SightMessage) {
      SightMessage sightMessage = logic.msgList[index].content as SightMessage;
      widget =  sightMessageItem(sightMessage);
    }
    return widget;
  }

  /// 底部工具栏+输入框
  Widget bottomTabUtil(){
    double height = logic.showBottom ? 250 : 60;
    return SafeArea(
      child: Stack(
        children: [
          /// 聊天页面主体
          Container(
            padding: EdgeInsets.symmetric(horizontal: 15,),
            height: height,
            color: Colors.grey.shade100,
            child: Column(
              children: [
                Container(
                  height: 60,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      RongWidget.imgAsset(logic.bottomType == 0 ? "keyboard.png" : "sound.png",onTap: (){
                        logic.showBottom = false;
                        logic.focusNode.unfocus();
                        /// 切换语音、文本输入
                        logic.bottomType == 0 ? logic.bottomType = 1 : logic.bottomType = 0;
                        logic.update();
                      },width: 30),
                      Expanded(
                        child: Padding(
                          child:  RongWidget.rongInput(
                            height: 40,
                            circular: 5,
                            bgColor: Colors.white,
                            maxLines: 1,
                            focusNode: logic.focusNode,
                            controller: logic.textEditingController,
                            onChanged: (v)=> logic.update(),
                            hintText: logic.bottomType == 0 ?  "长按说话~~" : "",
                            textAlign: logic.bottomType == 0 ? TextAlign.center : TextAlign.start,
                            enabled: logic.bottomType == 0 ? false : true,
                            onLongPress: logic.bottomType != 0 ? null : () async{
                              print("手指长按 触发说话");
                              onLongPressStartVoice(0);
                            },
                            onLongPressEnd: logic.bottomType != 0 ? null : (v) async{
                              print("手指松开 触发发送语音");
                              onLongPressStartVoice(1);
                            },
                            onTap: (){
                              // 点击输入框  关闭工具栏
                              logic.showBottom = false;
                            }
                          ),
                          padding: EdgeInsets.symmetric(horizontal: 15),
                        ),
                      ),
                      Row(
                        children: [
                          RongWidget.imgAsset("face.png",width: 25,onTap: (){
                            logic.focusNode.unfocus();
                            logic.bottomType = 1;
                            logic.setShowBottom();
                          }),
                          SizedBox(width: 15,),
                          logic.textEditingController.value.text == "" ? RongWidget.imgAsset("add_circle.png",onTap: (){
                            logic.focusNode.unfocus();
                            logic.bottomType = 2;
                            logic.setShowBottom();
                            logic.setListMax();
                          },width: 25):InkWell(
                            child: Container(
                              height: 35,
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                  color: Colors.green,
                                  borderRadius: BorderRadius.circular(4)
                              ),
                              padding: EdgeInsets.symmetric(horizontal: 15,vertical: 0),
                              child: Text('发送',style: TextStyle(
                                fontSize: 14,
                                color: Colors.white,
                              ),),
                            ),
                            onTap: (){
                              logic.sendTextMsg(logic.conversationType,logic.textEditingController.value.text,widget.targetId!);
                              RongIMClient.onMessageSend = (int? messageId, int? status, int? code)async{
                                print('messageId:$messageId  -----status:${status} ------ code:${code}');
                                Message? result =await RongIMClient.getMessage(messageId!);
                                if(status!=10){
                                  String timer = TimeUtil.convertDateTime(DateTime.now().millisecondsSinceEpoch);
                                  logic.msgList.insert(0,MessageEntity(true,result!.content!.conversationDigest(),timer,Constant.userDetailData!.userPic != null ?Constant.userDetailData!.userPic: getUserUtil().picUrl,result.content,result.sentTime,result,getUserUtil().nikeName,getUserUtil().ryUserId,getUserUtil().userId));
                                }
                                logic.setListMax();
                              };
                              logic.textEditingController.text = "";
                              logic.focusNode.unfocus();
                              logic.update();
                            },
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                Offstage(
                  child: Container(
                    width: Get.width,
                    height: height - 60,
                    child: buildBottomTabUtil(),
                  ),
                  offstage: !logic.showBottom,
                ),
              ],
            ),
          ),
          /// 录音时的gif展示
          buildExtraCenterWidget(),
        ],
      ),
    );
  }

  /// 构建工具栏
  Widget buildBottomTabUtil(){
    /// 语音
    // if(logic.bottomType == 0) return buildVoice();
    /// 表情包
    if(logic.bottomType == 1) return buildEmojiList();
    /// 更多工具
    if(logic.bottomType == 2) return buildMoreList();
    return SizedBox();
  }

  /// 构建表情包
  GridView buildEmojiList() {
    return GridView(
      scrollDirection: Axis.vertical,
      gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
        maxCrossAxisExtent: Get.width / 7,
      ),
      children: List.generate(
        logic.emojiList.length, (index) {
        return GestureDetector(
          onTap: () {
            //点击位置追加表情
            logic.textEditingController.text+=logic.emojiList[index];
            logic.update();
          },
          child: Center(
            widthFactor: Get.width / 7,
            heightFactor: Get.width / 7,
            child: Text(logic.emojiList[index], style: TextStyle(fontSize: 30)),
          ),
        );
      },
      ),
    );
  }

  /// 构建更多工具
  Widget buildMoreList(){
    return ListView(
      padding: EdgeInsets.all(0),
      children: [
        Wrap(
          runSpacing: 15,
          spacing: 30,
          children: [
            ...List.generate(logic.bottomUtilList.length, (index){
              return InkWell(
                onTap: (){
                  print(logic.bottomUtilList[index].name);
                  if(index == 0){
                    BottomSheetWidget.bottomImagePickWidget(callBack: (v) async{
                      print("选择的图片,直接发送图片消息$v");
                      Get.back();
                      if(v!=null){
                        logic.senImgMsg(v[0].path!);
                      }
                    },maxCount: 3);
                  }
                  if(index == 1){
                    BottomSheetWidget.bottomImagePickWidget(callBack: (v){
                      print("选择的视频,直接发送视频消息");
                      Get.back();
                      if(v!=null){
                        logic.senVideoMsg(v[0].path);
                      }
                    },galleryMode: GalleryMode.video,photoVideo: false,maxDuration: Duration(seconds: logic.secondsVideo));
                  }
                },
                child: Container(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      // RongWidget.imgAsset(
                      //   "${logic.bottomUtilList[index].pic}",
                      //   width: Get.width / 8,
                      //   height: Get.width / 8,
                      //   fit: BoxFit.scaleDown,
                      // ),
                      ClipRRect(
                        child: Container(
                          color: Colors.white,
                          padding: EdgeInsets.all(5),
                          child: Icon(index == 0 ? Icons.image : Icons.camera_alt,size: 35,),
                        ),
                        borderRadius:BorderRadius.circular(8),
                      ),
                      RongWidget.text("${logic.bottomUtilList[index].name}",color: Colors.grey.shade600,fonSize: 12),
                    ],
                  ),
                ),
              );
            }),
          ],
        ),
      ],
    );
  }

  /// 长按开始显示gif 0开始 1结束
  void onLongPressStartVoice(int type) {
    if (type==0) {
      logic.currentStatus = ConversationStatus.VoiceRecorder;
      MediaUtil.instance!.startRecordAudio();
    }else{
      logic.currentStatus = ConversationStatus.Normal;
      MediaUtil.instance!.stopRecordAudio((String? path, int duration) {
        print('path:$path');
        // //弹出一个框 用来播放 取消和发送语音
        // Get.bottomSheet(voiceWidget(path,duration));
        //点击发送语音消息
        logic.sendVoiceMessage(
            path,
            duration,
            privateUserId: logic.privateUserId,
            conversationType: logic.conversationType,
            sendCall: (status,messageId) async{
              Message? result =await RongIMClient.getMessage(messageId!);
              if(status==RCSentStatus.Sent){
                print("语音消息-$status");
                String timer = TimeUtil.convertDateTime(DateTime.now().millisecondsSinceEpoch);
                logic.msgList.insert(0,MessageEntity(true,result!.content!.conversationDigest(),timer,Constant.userDetailData!.userPic != null ?Constant.userDetailData!.userPic: getUserUtil().picUrl,result.content,result.sentTime,result,getUserUtil().nikeName,getUserUtil().ryUserId,getUserUtil().userId));
                logic.setListMax();
                logic.update();
              }
            }
        );
      });
    }
    logic.update();
  }

  /// 长按录制语音的 gif 动画
  Widget buildExtraCenterWidget() {
    if (logic.currentStatus == ConversationStatus.VoiceRecorder) {
      return RongWidget.buildVoiceRecorderWidget();
    } else {
      return RongWidget.buildEmptyWidget();
    }
  }

  /// 录音弹窗 item
  Widget voiceWidget(path,duration){
    return Container(
      height: 100,
      color: Colors.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          MaterialButton(
            child: RongWidget.text('播放',color: Colors.green,fonSize: 18),
            onPressed: () {
              //点击播放消息
              MediaUtil.getInstance()!.startPlayAudio(path);
            },
          ),
          Container(width: 1,height: 100,color: Colors.grey.shade200,),
          MaterialButton(
            child: RongWidget.text('发送',color: Colors.green,fonSize: 18),
            // iconSize: 32,
            onPressed: () async{

            },
          ),
        ],
      ),
    );
  }

  /// 播放消息语音 item
  Widget voicePlayWidget(index){
    VoiceMessage msg = logic.msgList[index].content as VoiceMessage;
    List<Widget> list = [];
    if (logic.msgList[index].message!.messageDirection == RCMessageDirection.Send) {
      list.add(SizedBox(
        width: 10,
      ));
      list.add(Text(msg.duration.toString() + "''", style: TextStyle(fontSize: 14),));
      list.add(SizedBox(
        width: 20,
      ));
      list.add(Container(
        width: 20,
        height: 20,
        child: Image.asset("assets/image/voice_icon.png"),
      ));
      list.add(SizedBox(
        width: 10,
      ));
    } else {
      list.add(SizedBox(
        width: 6,
      ));
      list.add(Container(
        width: 20,
        height: 20,
        child: Image.asset("assets/image/voice_icon_reverse.png"),
      ));
      list.add(SizedBox(
        width: 20,
      ));
      list.add(Text(msg.duration.toString() + "''"));
    }
    return GestureDetector(
      child: Container(
        width: 80,
        child:Row(children: list,mainAxisAlignment: logic.msgList[index].message!.messageDirection == RCMessageDirection.Send?
        MainAxisAlignment.end:MainAxisAlignment.start,),
      ),onTap: (){
      MediaUtil.instance!.startPlayAudio(msg.localPath??msg.remoteUrl);
    },
    );
    // return RongWidget.text('这是一条${logic.msgList[index].msg}，点击播放',onTap: (){
    //   print("播放语音: ${voiceMessage.duration},${voiceMessage.localPath}");
    //   Get.dialog(
    //     Center(
    //       child: Material(
    //         color: Colors.transparent,
    //         child: Container(
    //           width: 100,
    //           height: 100,
    //           color: Colors.white,
    //         ),
    //       ),
    //     ),
    //   );
    // });
  }

  /// 小视频消息  item
  Widget sightMessageItem(SightMessage msg) {
    if (true) {
      Widget previewW = Container(); //缩略图
      if (msg.content != null && msg.content!.length > 0) {
        Uint8List bytes = base64.decode(msg.content!);
        previewW = Image.memory(
          bytes,
          fit: BoxFit.fill,
        );
      }
      Widget bgWidget = Container(
        width: 100,
        height: 150,
        child: previewW,
      );
      Widget continerW = Container(
          width: 100,
          height: 150,
          child: Container(
            width: 50,
            height: 50,
            alignment: Alignment.center,
            child: Image.asset(
              "assets/image/play_sound.png",
              width: 50,
              height: 50,
            ),
          ));
      Widget timeW = Container(
        width: 100,
        height: 150,
        child: Container(
          width: 50,
          height: 20,
          alignment: Alignment.bottomLeft,
          child: Row(
            children: <Widget>[
              SizedBox(
                width: 5,
              ),
              Text(
                "${msg.duration}'s",
                style: TextStyle(color: Colors.white),
              ),
            ],
          ),
        ),
      );
      return InkWell(
        child: Stack(
          children: <Widget>[
            bgWidget,
            continerW,
            timeW,
          ],
        ),
        onTap: (){
          print(msg.content);
          Get.to(()=>ShowVideoPage(
            title: "",
            url: msg.remoteUrl,
          ));
          // 播放视频
          // Get.to(VideoPlayPage(message: widget.content,));
        },
      );
    }
  }

  /// 群组消息
  buildGroupNotificationMessage(index){
    GroupNotificationMessage group = logic.msgList[index].content as GroupNotificationMessage;
    if(widget.groupType ==1){//群主
      if(group.extra=='群主确认通知消息'){//确认消息
        print('确认消息');
        return buildOriginContentMap(group);
      }
    }
    return Container(
      //widget.message.originContentMap['message']
      padding: EdgeInsets.only(top: 15,bottom: 15),
      child: Text('${group.message}',
        style: TextStyle(fontSize: 14, color: Colors.grey,),
      ),
      alignment: Alignment.center,
      width: Get.width*0.7,
    );
  }

  /// 群组消息build
  buildOriginContentMap(GroupNotificationMessage group){
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          //widget.message.originContentMap['message']
          padding: EdgeInsets.only(top: 15,bottom: 15),
          child: Text('${group.message}',
            style: TextStyle(fontSize: 14, color: Colors.grey,),
          ),
          alignment: Alignment.center,
          width: Get.width*0.7,
        ),
        //群主需要处理的进群消息
        //&& widget.message.originContentMap['extra'] =="群主确认通知消息"
        //SpUtil.getBool(widget.message.messageId.toString())
        Builder(builder: (context){
          Widget sureButton=Container();
          //表示是群邀请人的消息  其他消息直接不加按钮
          // bool isShow =SpUtil.getBool(widget.message.messageId.toString());//true为同意进群 标为已读   false表示没有同意
          sureButton= InkWell(
            child: Text('${true?"已":"去"}确认',style: TextStyle(
                fontSize: 15,color: Colors.blue
            ),),
            onTap: (){
              // widget.back();
            },
          );
          return sureButton;
        })
      ],
    );
  }

  /// 消息撤回
  buildRecallNotificationMessage(index){
    RecallNotificationMessage recal= logic.msgList[index].content as RecallNotificationMessage;
    return Container(
      //widget.message.originContentMap['message']
      padding: EdgeInsets.only(top: 15,bottom: 15),
      child: Text('撤回消息:${recal.recallContent}',
        style: TextStyle(fontSize: 14, color: Colors.grey,),
      ),
      alignment: Alignment.center,
      width: Get.width*0.7,
    );
  }

  @override
  void dispose() {
    Get.delete<ChatLogic>();
    super.dispose();
    logic.focusNode.dispose();
    logic.messageListEventClose();
    logic.removeListener(() { logic.messageListEvent();});
    MediaUtil.getInstance()!.closeAudioSession();
    WidgetsBinding.instance!.removeObserver(this);
  }
}